import time
from PIL import Image
import numpy as np
import cv2
from matplotlib import pyplot as plt

# 灰度值计算
def grayscale(img):
    # 获取图片的像素矩阵
    pixels = img.tolist()

    sum_gray = []

    # 计算每个像素点的灰度值并在终端上显示
    height, width = len(pixels), len(pixels[0])
    for i in range(height):
        for j in range(width):
            # 获取RGB值
            # r, g, b = pixels[i, j]
            r, g, b = pixels[i][j]
            # 计算灰度值
            gray_value = int(0.299 * r + 0.587 * g + 0.114 * b)
            sum_gray.append(gray_value)
            # 在终端上显示灰度值

    # print(sum(sum_gray))
    return sum(sum_gray)

# 读入彩色图像
img = cv2.imread('image3.jpg')
# img = Image.open('image.jpg')
# gray = grayscale(img)

# 计算直方图
hist = np.zeros((256, ))
for i in range(img.shape[0]):
    for j in range(img.shape[1]):
        hist[img[i, j]] += 1

# 显示直方图
plt.title("Grayscale histogram")  # 灰度直方图
plt.xlabel("Grayscale value")   # 灰度值
plt.ylabel("Number of pixels")  # 像素数
plt.plot(hist)
plt.show()

# 定义旋转角度和旋转中心
angle = 15

def xuanzhuan(img, angle):
    center = (img.shape[1] / 2, img.shape[0] / 2)

    # 计算旋转矩阵
    M = np.float32([[np.cos(angle*np.pi/180), -np.sin(angle*np.pi/180), (1-np.cos(angle*np.pi/180))*center[0] + np.sin(angle*np.pi/180)*center[1]],
                    [np.sin(angle*np.pi/180), np.cos(angle*np.pi/180), (1-np.cos(angle*np.pi/180))*center[1] - np.sin(angle*np.pi/180)*center[0]]])



    # 对图像进行旋转变换
    rotated_img = np.zeros_like(img)
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            xy = np.array([j - center[0], i - center[1], 1]).reshape((3, 1))
            # print(xy.shape)
            xy_rotated = M @ xy + center
            x, y = xy_rotated[:2, 0]
            if x >= 0 and x < img.shape[1] and y >= 0 and y < img.shape[0]:
                rotated_img[int(i), int(j), :] = img[int(y), int(x), :]

    return rotated_img

# 输出旋转参数
start_time = time.time()
rotated_img = xuanzhuan(img, angle)
end_time = time.time()
cv2.imwrite('rotated_image7.jpg', rotated_img)

angle2 = -1*angle
rotated_img2 = xuanzhuan(rotated_img, angle2)
cv2.imwrite('rotated_image8.jpg', rotated_img2)

time1 = end_time - start_time
print(f"旋转了{angle}角度运行的时长为：{time1}s")


gray1 = grayscale(rotated_img)
gray2 = grayscale(rotated_img2)
if (gray2 - gray1) == 0:
    print("灰度值差异为0")
else:
    print(f"灰度值有差异，差异值为{gray2-gray1}")


